package com.guazai.apiinterface.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.google.gson.*;
import com.guazai.apiinterface.request.BaseRequest;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author guazai
 */
@RestController
@Slf4j
public class InterfaceController {

    private final DatabaseReader dbReader;

    private Cache<String, String> cache = Caffeine.newBuilder()
            .maximumSize(100)
            .expireAfterWrite(60, TimeUnit.MINUTES)
            .build();

    public InterfaceController() throws IOException {
        log.info("正在加载GeoIP2 数据库文件......");
        // 加载 GeoIP2 数据库文件
        InputStream databaseStream = new ClassPathResource("GeoLite2-city.mmdb").getInputStream();
        log.info("加载文件成功");
        // 初始化数据库阅读器
        this.dbReader = new DatabaseReader.Builder(databaseStream).build();
    }

    Gson gson = new Gson();

    /**
     * 获取用户姓名
     *
     * @param baseRequest
     * @return
     */
    @PostMapping("/name/user")
    public String getNameByUser(@RequestBody BaseRequest baseRequest) {
        if (baseRequest == null) {
            return "null";
        }
        //获取json参数
        String json = baseRequest.getParamsJson();
        //如果json不为空，获取json中的name参数
        if (!"{}".equals(json)) {
            JsonElement jsonElement = JsonParser.parseString(baseRequest.getParamsJson());
            JsonObject jsonObject = jsonElement.getAsJsonObject();
            JsonElement element = jsonObject.get("name");
            if (element == null) {
                return null;
            }
            String name = element.getAsString();
            return "POST  " + "你的名字是：" + name;
        } else {
            return null;
        }
    }

    /**
     * 获取毒鸡汤
     *
     * @return 返回毒鸡汤
     */
    @GetMapping("/poisonousChickenSoup")
    public String getPoisonousChickenSoup() {
        String json = HttpRequest.get("https://api.btstu.cn/yan/api.php?charset=utf-8&encode=json").execute().body();
        return json;
    }

    /**
     * 访问微博热搜接口
     *
     * @return
     */
    @GetMapping("/weiboHotSearch")
    public String getWeiboHotSearch() {
        log.info("调用微博热搜接口");
        String res = cache.get("WEIBO_HOT_SEARCH", k -> {
            // 1. 访问微博热搜接口
            String json = HttpRequest.get("https://weibo.com/ajax/side/hotSearch").execute().body();
            //获得jsonElement
            JsonElement jsonElement = JsonParser.parseString(json);
            //获得jsonObject
            JsonObject jsonObject = jsonElement.getAsJsonObject();
            //获得array
            JsonObject data = jsonObject.getAsJsonObject("data");
            JsonArray hot = data.getAsJsonArray("realtime");
            //将array转成json
            String result = gson.toJson(hot);
            result = "{\n" + "\"weibohotSearch\": " + result + "\n}";
            return result;
        });
        return res;
    }

    /**
     * 获取星座运势
     *
     * @return 返回星座运势
     */
    @GetMapping("/horoscope")
    public String getHoroscope(@RequestBody BaseRequest request) {
        //获取json参数
        String json = request.getParamsJson();
        //如果json不为空，获取json中的参数
        String type = null;
        String time = null;
        if (!"{}".equals(json)) {
            JsonElement jsonElement = JsonParser.parseString(request.getParamsJson());
            JsonObject jsonObject = jsonElement.getAsJsonObject();
            JsonElement typeElement = jsonObject.get("type");
            JsonElement timeElement = jsonObject.get("time");
            //判断是否为空
            if (!ObjectUtil.isAllNotEmpty(typeElement, timeElement)) {
                return null;
            }
            type = typeElement.getAsString();
            time = timeElement.getAsString();
        } else {
            //如果参数为空，返回null
            return null;
        }
        //如果任意参数为空，返回null
        if (StringUtils.isAnyBlank(type, time)) {
            return null;
        }
        //发送请求
        String responseJson = HttpRequest.get("https://api.vvhan.com/api/horoscope?type=" + type + "&time=" + time).execute().body();
        //处理返回结果
        JsonElement jsonElement = JsonParser.parseString(responseJson);
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        JsonElement e = jsonObject.get("data");
        String data = e.toString();
        return data;
    }

    /**
     * 获取用户公网ip地址和城市信息
     */
    @GetMapping("/publicIp")
    public String getPublicIp(@RequestBody BaseRequest baseRequest) {
        //获得ipAddress
        JsonElement jsonElement = JsonParser.parseString(baseRequest.getParamsJson());
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        JsonElement ipAddressElement = jsonObject.get("ipAddress");
        if (ipAddressElement == null) {
            return null;
        }
        String ipAddress = ipAddressElement.getAsString();
        try {
            //获取ip信息
            InetAddress inetAddress = InetAddress.getByName(ipAddress);
            CityResponse cityResponse = dbReader.city(inetAddress);
            //将信息封装为一个map
            Map<String, String> map = new HashMap<>();
            map.put("ipAddress", ipAddress);
            map.put("city", cityResponse.getCity().getName());
            map.put("country", cityResponse.getCountry().getName());
            String json = gson.toJson(map);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取随机壁纸
     *
     * @return
     */
    @GetMapping("/randomWallpaper")
    public String getRandomWallpaper() {
        String wallpaperJson = HttpRequest.get("https://btstu.cn/sjbz/api.php?lx=dongman&format=json").execute().body();
        //处理返回结果
        JsonElement jsonElement = JsonParser.parseString(wallpaperJson);
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        JsonElement e = jsonObject.get("imgurl");
        String data = e.getAsString();
        return data;
    }

    /**
     * 获取网站图标
     *
     * @return
     */
    @GetMapping("/webFaviconIcon")
    public String getWebFaviconIcon(@RequestBody BaseRequest request) {
        String url = null;
        //获取json参数
        String json = request.getParamsJson();
        if ("{}".equals(json)) {
            //如果参数为空，返回null
            return null;
        }
        JsonElement jsonElement = JsonParser.parseString(request.getParamsJson());
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        JsonElement urlElement = jsonObject.get("url");
        url = urlElement.getAsString();
        //判断是否为空
        if (ObjectUtil.isEmpty(urlElement)) {
            return null;
        }
        //如果任意参数为空，返回null
        if (StringUtils.isBlank(url)) {
            return null;
        }
        String image = HttpRequest.get("https://btstu.cn/getfav/api.php?url=" + url).execute().body();
        return image;
    }

    /**
     * 土味情话
     *
     * @return
     */
    @GetMapping("/loveTalk")
    public String getLoveTalk() {
        String loveTalk = HttpRequest.get("https://api.vvhan.com/api/love").execute().body();
        return loveTalk;
    }

    /**
     * 获取天气信息
     *
     * @return
     */
    @GetMapping("/weather")
    public String getWeather() {
        String weatherJson = HttpRequest.get("https://api.vvhan.com/api/weather").execute().body();
        return weatherJson;
    }
}
